/* eslint-disable consistent-return */

import React from 'react';
import isEqual from 'lodash/isEqual';
import { SearchOutlined, UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Select, Spin, Input, Row, Col, Button, Card, InputNumber, Upload, message } from 'antd';
import TextArea from 'antd/lib/input/TextArea';
import router from 'umi/router';
import FooterToolbar from '@/components/FooterToolbar';
import { requestHeadersMd5 } from '@/utils/utils';
import HOCSelect from '@/components/AntDesign/Select';

const { Option } = Select;
const FormItem = Form.Item;
@Form.create()
class AddTmp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isCusValidate: true,
      fileList: [],
      sendId: '',
      affix: '',
      updateVo: {},
    };
  }

  static getDerivedStateFromProps(nextProps, preState) {
    if (isEqual(nextProps.updateVo, preState.updateVo)) {
      return null;
    }
    return {
      updateVo: nextProps.updateVo,
      affix: nextProps.updateVo.affix,
      sendId: nextProps.updateVo.sendId,
      dataSource: nextProps.updateVo.dataSource,
    };
  }

  search = value => {
    const { dispatch } = this.props;
    if (value.trim().length) {
      const values = {
        empName: value.trim(),
      };
      dispatch({
        type: 'rebate/fetchEmpNameList',
        payload: values,
      }).then(() => {});
    }
  };

  empData = value => {
    const { empNameList, form } = this.props;
    if (empNameList) {
      empNameList.map(item => {
        if (item.sendId === value) {
          this.setState({
            sendId: item.sendId,
            dataSource: item.dataSource,
          });
          form.setFieldsValue({
            certNo: item.certNo,
          });
        }
        return true;
      });
    }
  };

  save = () => {
    const { form, saveClick } = this.props;
    const { sendId, dataSource, affix } = this.state;
    this.setState(
      {
        isCusValidate: false,
      },
      () => {
        form.validateFieldsAndScroll((err, values) => {
          if (!err) {
            saveClick({ ...values, sendId, dataSource, affix });
          }
        });
      }
    );
  };

  valiFunc = (rule, value) => {
    this.setState({
      certNo: value,
    });
  };

  cancle = () => {
    router.goBack();
  };

  idVailFunc = () => {
    const { certNo } = this.state;
    const { dispatch, form } = this.props;
    const patt = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (patt.test(certNo)) {
      this.setState({
        valiStatus: 'success',
        tip: null,
      });
      if (certNo.trim().length) {
        const values = {
          certNo: certNo.trim(),
        };
        dispatch({
          type: 'rebate/fetchEmpNameList',
          payload: values,
        }).then(resp => {
          if (resp.success) {
            if (resp.data && resp.data.length === 0) {
              message.warning('当前所输的证件号不存在，请检查 ');
            } else {
              this.setState({
                sendId: resp.data[0].sendId,
                dataSource: resp.data[0].dataSource,
              });
              form.setFieldsValue({
                empName: resp.data[0].empName,
              });
            }
          } else {
            message.error(resp.message || '服务器错误');
          }
        });
      }
    } else {
      this.setState({
        valiStatus: 'error',
        tip: '请输入正确格式的身份证号',
      });
    }
  };

  handleFile = affixList => {
    const arr = [];
    affixList.split(',').map(value => {
      const tempJson = {};
      const [uid, name] = value.split('|');
      tempJson.uid = uid;
      tempJson.name = name;
      arr.push(tempJson);
      return true;
    });
    return arr;
  };

  normFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  componentDidMount = () => {};

  formatFileList = fileList => {
    const arr = [];
    let str = '';
    fileList.map(value => {
      arr.push(`${value.uid}|${value.name}`);
      return true;
    });
    str = arr.join(',');
    return str;
  };

  formatFileStr = fileList => {
    const oldFileList = fileList.filter(item => !item.response);
    const newFileList = fileList.filter(item => item.response && item.response.success);
    const arr = [];
    const arr2 = [];
    let str = '';
    newFileList.forEach(item => {
      const json = {};
      if (item.response.success) {
        const [uid, name] = item.response.data.split('|');
        json.uid = uid;
        json.name = name;
        arr.push(json);
      }
    });
    const tempArr = arr.concat(oldFileList);
    tempArr.forEach(value => {
      arr2.push(`${value.uid}|${value.name}`);
    });
    str = arr2.join(',');
    return str;
  };

  render() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const { loading } = this.props;
    const { empNameList, updateVo, serviceDicList } = this.props;
    const { fileList, valiStatus, tip, isCusValidate } = this.state;
    // console.log('updateVo.empName', updateVo.empName);
    const props = {
      name: 'file',
      action: '/osApi/fileServer/uploadFile',
      headers: {
        authorization: 'authorization-text',
        ...requestHeadersMd5(),
      },
      beforeUpload: (file, fileList1) => {
        const isLt5M = file.size / 1024 / 1024 < 5; // 文件限制5M
        if (!isLt5M) {
          message.error('文件大小不允许超过5M,请重新上传！');
          fileList1.splice(fileList1.length - 1, 1);
          return false;
        }
        if (fileList1.length === 10) {
          message.warning('凭证最多只能上传10个，请检查');
          fileList1.splice(fileList.length - 1, 1);
          this.setState({
            fileList: fileList.splice(10, 1),
          });

          return false;
        }
      },
      onChange: info => {
        if (info.file.status === 'done') {
          const affix = this.formatFileStr(info.fileList);

          this.setState({
            affix,
            fileList: info.fileList,
          });
          message.success(`${info.file.name} 上传成功！`);
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 上传失败！`);
        }
      },
    };
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 8,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 16,
        },
      },
    };

    return (
      <div>
        <Card>
          <Row>
            <Row>
              <Col span={14} offset={3}>
                <FormItem {...formItemLayout} label={<span>员工姓名 </span>}>
                  {getFieldDecorator('empName', {
                    rules: [
                      {
                        required: true,
                        message: '只能输入汉字或者英文',
                      },
                    ],
                    initialValue: updateVo.empName,
                  })(
                    <HOCSelect
                      placeholder="请输入关键字检索"
                      disabled={!!updateVo.empName}
                      {...this.props}
                      style={{ width: '100%' }}
                      showSearch
                      optionFilterProp="children"
                      showArrow={false}
                      onSearch={this.search}
                      onSelect={this.empData}
                      notFoundContent={loading ? <Spin size="small" /> : null}
                    >
                      {empNameList.length &&
                        empNameList.map(item => <Option key={item.sendId}>{item.empName}</Option>)}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={14} offset={3}>
                <FormItem
                  {...formItemLayout}
                  label="证件号:"
                  hasFeedback
                  validateStatus={valiStatus}
                  help={tip}
                >
                  {getFieldDecorator('certNo', {
                    rules: [
                      {
                        required: true,
                        message: '请输入证件号',
                        validator: isCusValidate ? this.valiFunc : undefined,
                      },
                    ],
                    initialValue: updateVo.certNo,
                  })(<Input placeholder="请输入证件号" disabled={!!updateVo.certNo} />)}
                </FormItem>
              </Col>
              <Col span={4} style={{ marginLeft: 10, marginTop: 5 }}>
                <FormItem {...formItemLayout}>
                  <span onClick={this.idVailFunc}>
                    <SearchOutlined style={{ fontSize: '16px' }} />
                  </span>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={14} offset={3}>
                <FormItem {...formItemLayout} label={<span>服务类型</span>}>
                  {getFieldDecorator('serTypeId', {
                    rules: [
                      {
                        required: true,
                        message: '请选择服务类型',
                      },
                    ],
                    initialValue: updateVo.serTypeId,
                  })(
                    <Select
                      style={{ width: '100%' }}
                      placeholder="请选择服务类型"
                      disabled={!!updateVo.serTypeId}
                    >
                      {serviceDicList.map(value => (
                        <Option key={value.serTypeId}>{value.serTypeIdName}</Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={14} offset={3}>
                <FormItem {...formItemLayout} label={<span>收款方信息</span>}>
                  {getFieldDecorator('payeeName', {
                    rules: [
                      {
                        required: false,
                        message: '请输入不超过50个字符的收款方信息',
                        max: 50,
                      },
                    ],
                    initialValue: updateVo.payeeName,
                  })(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={14} offset={3}>
                <FormItem {...formItemLayout} label={<span>收款方银行账户</span>}>
                  {getFieldDecorator('payeeBankcardNo', {
                    rules: [
                      {
                        required: false,
                        message: '请输入不超过50个字符的收款方银行账户',
                        pattern: /^\d+$|^\d+[.]?\d+$/,
                        max: 50,
                      },
                    ],
                    initialValue: updateVo.payeeBankcardNo,
                  })(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={14} offset={3}>
                <FormItem {...formItemLayout} label={<span>开户行信息</span>}>
                  {getFieldDecorator('payeeBankOfDepo', {
                    rules: [
                      {
                        required: false,
                        message: '请输入不超过50个字符的开户行信息',
                        max: 50,
                      },
                    ],
                    initialValue: updateVo.payeeBankOfDepo,
                  })(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={14} offset={3}>
                <FormItem {...formItemLayout} label={<span>报销金额（元）</span>}>
                  {getFieldDecorator('reimbAmt', {
                    rules: [
                      {
                        required: true,
                        message: '请输入小数点不超过2位的数字报销金额（元）',
                        pattern: /^[0-9]{0,7}(\.[0-9]{1,2})?$/,
                      },
                    ],
                    initialValue: updateVo.reimbAmt && updateVo.reimbAmt.toFixed(2),
                  })(<InputNumber placeholder="请输入" step={0.01} style={{ width: '100%' }} />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={14} offset={3}>
                <FormItem {...formItemLayout} label={<span>本次返款金额</span>}>
                  {getFieldDecorator('refundAmt', {
                    rules: [
                      {
                        required: true,
                        message: '请输入小数点不超过2位的本次返款金额',
                        pattern: /^[0-9]{0,7}(\.[0-9]{1,2})?$/,
                      },
                    ],
                    initialValue: updateVo.refundAmt && updateVo.refundAmt.toFixed(2),
                  })(<InputNumber placeholder="请输入" step={0.01} style={{ width: '100%' }} />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={14} offset={3}>
                <FormItem {...formItemLayout} label={<span>返款备注</span>}>
                  {getFieldDecorator('remark', {
                    rules: [
                      {
                        required: false,
                        message: '请输入不超过200个字符的返款备注',
                        max: 200,
                      },
                    ],
                    initialValue: updateVo.remark,
                  })(<TextArea placeholder="请输入" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={14} offset={3}>
                <FormItem {...formItemLayout} label="上传凭证">
                  {getFieldDecorator('affix', {
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue: updateVo.affix ? this.handleFile(updateVo.affix) : [],
                  })(
                    <Upload {...props}>
                      <Button>
                        <UploadOutlined /> 点击上传
                      </Button>
                    </Upload>
                  )}
                </FormItem>
              </Col>
            </Row>
          </Row>
        </Card>
        <FooterToolbar style={{ width: '100%' }}>
          <Button onClick={this.cancle}>取消</Button>
          <Button type="primary" onClick={this.save}>
            保存
          </Button>
        </FooterToolbar>
      </div>
    );
  }
}
export default AddTmp;
